import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";
import { Form, Table, Input, Space, Button } from "tdesign-react";
import { AddIcon, SearchIcon } from "tdesign-icons-react";
import type { TableProps } from 'tdesign-react';
import "./index.scss";

// ref调用
interface TableListRefMethods {
  someMethod(): () => void;
}

type FilterData = {
  keyword: string;
  type: string | number;
  status: string | number;
};

/**
 * table表格
 * @param props
 * @returns
 */
const TableList = forwardRef((props: { filter: FilterData }, ref) => {
  const { filter } = props;
  const [total, setTotal] = useState(0);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [data, setData] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<Array<string | number>>([]);
  // 使用 useImperativeHandle 来定制暴露给父组件的实例值
  const internalMethod = () => {
    loadData();
  };

  useImperativeHandle(ref, () => ({
    someMethod: () => internalMethod(),
  }));
  useEffect(() => {
    loadData();
  }, []);

  const loadData = () => {
    setIsLoading(true);
    setTimeout(() => {
      for (let i = 0; i < 20; i++) {
        data.push({
          index: i + 1,
          applicant: ["贾明", "张三", "王芳"][i % 3],
          status: i % 3,
          channel: ["电子签署", "纸质签署", "纸质签署"][i % 3],
          detail: {
            email: ["w.cezkdudy@lhll.au", "r.nmgw@peurezgn.sl", "p.cumx@rampblpa.ru"][i % 3],
          },
          matters: ["宣传物料制作费用", "algolia 服务报销", "相关周边制作费", "激励奖品快递费"][i % 4],
          time: [2, 3, 1, 4][i % 4],
          createTime: ["2022-01-01", "2022-02-01", "2022-03-01", "2022-04-01", "2022-05-01"][i % 4],
        });
        setData(data);
        setTotal(data.length);
      }
      setIsLoading(false);
    }, 1500);
    console.log(filter);
  };

  const onSelectChange: TableProps['onSelectChange'] = (value, { selectedRowData }) => {
    console.log(value, selectedRowData);
    setSelectedRowKeys(value);
  };

  const columns = [
    {
      colKey: 'row-select',
      type: 'multiple',
      // 禁用行选中方式一：使用 disabled 禁用行（示例代码有效，勿删）。disabled 参数：{row: RowData; rowIndex: number })
      // 这种方式禁用行选中，当前行会添加行类名 t-table__row--disabled，禁用行文字变灰
      // disabled: ({ rowIndex }) => rowIndex === 1 || rowIndex === 3,
  
      // 禁用行选中方式二：使用 checkProps 禁用行（示例代码有效，勿删）
      // 这种方式禁用行选中，行文本不会变灰
      // checkProps: ({ rowIndex }) => ({ disabled: rowIndex % 2 !== 0, title: rowIndex % 2 !== 0 ? '不可选' : null }),
      width: 50,
    },
    { colKey: "applicant", title: "用户名", width: "100", left: true },
    { colKey: "status", title: "申请状态"},
    { colKey: "channel", title: "签署方式" },
    { colKey: "detail.email", title: "邮箱地址", ellipsis: true },
    { colKey: "createTime", title: "申请时间" },
  ]

  return (
    <Table
      loading={isLoading}
      data={data}
      columns={columns}
      rowKey="index"
      bordered
      tableLayout="auto"
      cellEmptyContent={"-"}
      height='500px'
      className="table"
      resizable
      paginationAffixedBottom={true}
      selectOnRowClick={true}
      selectedRowKeys={selectedRowKeys}
      // 与pagination对齐
      pagination={{
        defaultCurrent: 1,
        defaultPageSize: 5,
        total,
        showJumper: true,
        onChange(pageInfo) {
          console.log(pageInfo, "onChange pageInfo");
        },
        onCurrentChange(current, pageInfo) {
          console.log(current, pageInfo, "onCurrentChange current");
        },
        onPageSizeChange(size, pageInfo) {
          console.log(size, pageInfo, "onPageSizeChange size");
        },
      }}
      onPageChange={(pageInfo) => {
        console.log(pageInfo, "onPageChange");
      }}
      onRowClick={({ row, index, e }) => {
        console.log("onRowClick", { row, index, e });
      }}
      onSelectChange={onSelectChange}
    />
  );
});

const UserList: React.FC = () => {
  const tabListRef = useRef<TableListRefMethods>(null);
  const [filter, setFilter] = useState<FilterData>({
    keyword: "",
    type: "",
    status: "",
  });

  const [filterData, setFilterData] = useState<FilterData>({
    keyword: "",
    type: "",
    status: "",
  });

  const setValue = (name: string, value: string) => {
    setFilter({
      ...filter,
      [name]: value,
    });
  };

  // 搜索事件
  const onSearch = () => {
    setFilterData(filter);
    if (tabListRef.current) {
      tabListRef.current.someMethod();
    }
  };

  return (
    <div className="user-list">
      {/* 搜索拦 */}
      <div className="search-bar__wrap">
        <Space direction="vertical">
          <Form layout="inline" labelWidth={60}>
            <Form.FormItem label="名字" name="name">
              <Input onChange={(val) => setValue("name", val)} />
            </Form.FormItem>
            <Form.FormItem label="密码" name="password">
              <Input onChange={(val) => setValue("type", val)} />
            </Form.FormItem>
            <Form.FormItem label="" name="">
              <Button icon={<SearchIcon />} onClick={onSearch}>
                搜索
              </Button>
            </Form.FormItem>
          </Form>
        </Space>
      </div>

      {/* 工具栏 */}
      <div className="tool-bar__wrap">
        <Button><AddIcon />新增</Button>
      </div>

      {/* 表格内容 */}
      <div className="table-content__wrapper">
        <TableList ref={tabListRef} filter={filterData} />
      </div>
    </div>
  );
};

export default UserList;
